﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Role;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Role
{
    public class DelparmentRoleHandler : IRequestHandler<DelparmentRoleCommon, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountRoleModel> accountRoleRepo;

        public DelparmentRoleHandler(IBaseRepository<AccountRoleModel> accountRoleRepo)
        {
            this.accountRoleRepo = accountRoleRepo;
        }
        public async Task<ApiResult<int>> Handle(DelparmentRoleCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var result = accountRoleRepo.GetAll().Where(x=>x.RoleId==request.RoleId).ToList();
               await accountRoleRepo.Del(result);
                List<AccountRoleModel> models = new List<AccountRoleModel>();

                foreach (var item in request.UserId)
                {
                    models.Add(new AccountRoleModel()
                    {
                        UserId=item,
                        RoleId=request.RoleId,

                    });
                  
                }

                int count =await accountRoleRepo.AddAll(models);


                if (count > 0)
                {
                    res.Code = ApiEnum.Success;
                    res.Data= count;
                    res.Message = "分配成功";
                  

                }
                else
                {
                    res.Code = ApiEnum.Error;
                    res.Data = count;
                    res.Message = "分配失败";
                 
                }

                tran.Complete();
                return await Task.FromResult(res);


            }

        }
    }
}
